package com.seckill.zk;

import com.seckill.service.SeckillService;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author wangzhilong
 * @date 2019-06-19
 */
@Component
public class JvmCacheWatcher implements Watcher {

    private Logger logger = LoggerFactory.getLogger(JvmCacheWatcher.class);

    @Autowired
    private SeckillService seckillService;

    private ZooKeeper zooKeeper ;

    public void setZooKeeper(ZooKeeper zooKeeper) {
        this.zooKeeper = zooKeeper;
    }

    @Override
    public void process(WatchedEvent event) {
        try {
            if (event.getType() == Event.EventType.NodeDataChanged) {
                String path = event.getPath();
                String soldOutFlag = new String(zooKeeper.getData(path, true, new Stat()));
                logger.info("Zookeeper节点数据变动：path={},value={}",path,soldOutFlag);
                if ("false".equals(soldOutFlag)) {
                    String bookId = path.substring(path.lastIndexOf("/") + 1);
                    //清楚缓存标记
                    seckillService.removeJvmCache(Integer.valueOf(bookId));
                    logger.info("=======清除商品{}内存售完标记。",bookId);
                }
            }
        } catch (Exception e) {
            logger.error("zookeeper节点数据变动异常：",e);
        }
    }
}
